package com.spark.common.helper

import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.Gravity.BOTTOM
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.spark.common.R
import kotlinx.android.synthetic.main.dal_date_picker.*
import java.text.SimpleDateFormat
import java.util.*

/**
 * 选择日期
 */
class DatePickerDiaFragment : DialogFragment() {

    private var onDateTapedListener: OnDateTapedListener? = null

    companion object {

        fun newInstance(): DatePickerDiaFragment {
            val args = Bundle()
            val fragment = DatePickerDiaFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.DialogFragmentAnimStyle)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.dal_date_picker, container)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dialog.window.setWindowAnimations(R.style.DialogFragmentAnimStyle)
        initLayout()
        initView()
    }

    private fun initView() {

        val sdf = SimpleDateFormat("yy.MM.dd", Locale.getDefault())

        calendar.setOnDateChangeListener { view, year, month, dayOfMonth ->
            //val dayStr = sdf.format(Date(year, month, dayOfMonth))
            val cal = Calendar.getInstance()
            cal.set(year, month, dayOfMonth)
            onDateTapedListener?.onDateTaped(cal.timeInMillis)
            dismiss()
        }
        ll_content.setOnClickListener { dismiss() }
    }

    /**
     * 初始化布局
     */
    private fun initLayout() {
        val screenWidth = resources.displayMetrics.widthPixels
        val screenHeight = resources.displayMetrics.heightPixels

        var lp = dialog.window.attributes
        lp.height = screenHeight / 5 * 3
        lp.gravity = BOTTOM
        dialog.window.attributes = lp
    }


    interface OnDateTapedListener {
        fun onDateTaped(date: Long)
    }

    fun setOnDateTapedListener(listener: (Long) -> Unit) {
        onDateTapedListener = object : OnDateTapedListener {
            override fun onDateTaped(date: Long) {
                listener(date)
            }
        }
    }

    fun setOnDateTapedListener(listener: OnDateTapedListener?) {
        if (listener == null) {
            return
        }
        onDateTapedListener = listener
    }

}
